/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisyimport.cli;

import cz.mzk.kramerius.commons.PropertyLoader;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class IndexManuscriptAction implements Action {

    private static final Logger logger = Logger.getLogger(IndexManuscriptAction.class.getName());
    private static final String PROP_KRAMERIUS_URL = "Kramerius.url";
    private static final String PROP_KRAMERIUS_USER = "Kramerius.user";
    private static final String PROP_KRAMERIUS_PASSWORD = "Kramerius.password";
    private final Properties properties;
    private String uuid;

    public IndexManuscriptAction(Properties properties) {
        this.properties = properties;
    }

    public ActionResult run(ActionResult previousActionResult) {
        try {
            uuid = uuidFromPreviousAction(previousActionResult);
            URL url = buildIndexUrl(uuid, properties);
            System.out.println(url.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            while (reader.ready()) {
                System.out.println(reader.readLine());
            }
            in.close();
            return new ActionResult(true, previousActionResult.getResultData());
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
            return new ActionResult(false, previousActionResult.getResultData());
        }
    }

    private URL buildIndexUrl(String uuid, Properties properties) throws MalformedURLException {
        PropertyLoader loader = new PropertyLoader(properties);
        String urlPrefix = loader.loadString(PROP_KRAMERIUS_URL);
        String userName = loader.loadString(PROP_KRAMERIUS_USER);
        String password = loader.loadString(PROP_KRAMERIUS_PASSWORD);
        String url = urlPrefix + "/lr?action=start&def=reindex&out=text&params=fromKrameriusModel," + uuid + "," + "reindexing_manuscript_" + uuid + "&userName=" + userName + "&pswd=" + password;
        return new URL(url);
    }

    private String uuidFromPreviousAction(ActionResult previousActionResult) throws Exception {
        Object previousResultData = previousActionResult.getResultData();
        if (previousResultData instanceof String) {
            String pid = (String) previousResultData;
            return pid.substring(5);
        } else {
            throw new Exception("Result of previous action didn't contain pid to index");
        }
    }
}
